package cn.micai.base.asyn;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 描述：Java8 CompletableFuture
 可以定义回调函数， 子线程执行完后，会触发回调函数
 * <p>
 *     步骤：

 1）CompletableFuture.supplyAsync（），定义要执行的异步任务

 2）cupdResult.thenAccept(new Consumer<String>() ， 重写accept（）方法去定义回调函数
 *
 * @author: 赵新国
 * @date: 2018/5/25 16:07
 */
public class J8ComFuture3 {

    public static void main(String [] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        // get msg from tc
        System.out.println("Got reqeust from TC");

        // prepare RM
        System.out.println("prepare RM msg");

        // trigger cupd
        CompletableFuture<String> cupdResult = CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                try {
                    System.out.println("sleep b4");
                    TimeUnit.SECONDS.sleep(5);
                    System.out.println("sleep after");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "msg from CUPD";
            }
        }, executorService);

        // reture cupd
        cupdResult.thenAccept(new Consumer<String>() {
            // callback method
            @Override
            public void accept(String s) {
                System.out.println("return msg to TC=" + s);
            }
        });

        // return RM
        System.out.println("return RM msg to customer");

    }

}
